package com.sylingd.blog.ui.index

import android.app.Fragment
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.sylingd.blog.R
import com.sylingd.blog.bean.Article
import com.sylingd.blog.lib.Api
import com.sylingd.blog.ui.adapter.ArticleAdapter


class ListFragment: Fragment() {

	companion object {
		const val ALL_ID = -1
		const val TYPE_ID = 1
		const val TYPE_TAG = 2
		fun create(id: Int): ListFragment {
			val f = ListFragment()
			val args = Bundle()
			args.putInt("id", id)
			args.putInt("type", TYPE_ID)
			f.arguments = args
			return f
		}
		fun create(tag: String): ListFragment {
			val f = ListFragment()
			val args = Bundle()
			args.putString("tag", tag)
			args.putInt("type", TYPE_TAG)
			f.arguments = args
			return f
		}
	}

	private val type: Int by lazy {
		arguments.getInt("type")
	}
	private val currentId: Int by lazy {
		arguments.getInt("id")
	}
	private val currentTag: String by lazy {
		arguments.getString("tag")
	}

	private lateinit var mainView: SwipeRefreshLayout
	private lateinit var mainList: RecyclerView
	private var loaded = false
	private var lastPage = 1

	override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
		mainView = inflater!!.inflate(R.layout.fragment_list, null) as SwipeRefreshLayout
		mainList = mainView.findViewById(R.id.listContent)

		//下拉刷新
		mainView.setColorSchemeColors(
				ContextCompat.getColor(activity.applicationContext, android.R.color.holo_blue_bright),
				ContextCompat.getColor(activity.applicationContext, android.R.color.holo_green_light),
				ContextCompat.getColor(activity.applicationContext, android.R.color.holo_orange_light),
				ContextCompat.getColor(activity.applicationContext, android.R.color.holo_red_light))
		mainView.setOnRefreshListener {
			loadNewest()
		}
		//绑定Adapter
		mainList.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
		mainList.adapter = ArticleAdapter(activity, R.layout.item_article, this@ListFragment)
		//上拉更多
		mainList.addOnScrollListener(object: RecyclerView.OnScrollListener() {
			override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
				super.onScrolled(recyclerView, dx, dy)
				if (recyclerView != null) {
					val layoutManager = recyclerView.layoutManager as LinearLayoutManager
					val lastChildBottom = layoutManager.getChildAt(layoutManager.childCount - 1).bottom
					val recyclerBottom = recyclerView.bottom - recyclerView.paddingBottom
					if (lastChildBottom == recyclerBottom
							&& layoutManager.findLastVisibleItemPosition() == layoutManager.itemCount - 1
							&& !((recyclerView.parent as SwipeRefreshLayout).isRefreshing)
							&& dy >= 0) {
						loadOlder()
					}
				}
			}
		})

		if (!loaded) {
			loadNewest()
			loaded = true
		}

		return mainView
	}

	//加载列表
	private fun loadNewest() {
		//显示加载圈
		mainView.isRefreshing = true
		val adapter = mainList.adapter as ArticleAdapter
		loadArticles(1, { data ->
			val gsonObj = Gson()
			mainView.post({
				var i = data.size()
				while (i-- > 0) {
					val o = gsonObj.fromJson(data[i], Article::class.java)
					if (adapter.isExists(o)) {
						break
					} else {
						adapter.addToStart(o)
					}
				}
				mainView.isRefreshing = false
			})
		})
	}
	private fun loadOlder() {
		//显示加载圈
		mainView.isRefreshing = true
		val adapter = mainList.adapter as ArticleAdapter
		loadArticles(lastPage + 1, { data ->
			val gsonObj = Gson()
			mainView.post({
				var hasMore = false
				for (i in data) {
					val o = gsonObj.fromJson(i, Article::class.java)
					if (adapter.isExists(o)) {
						break
					} else {
						hasMore = true
						adapter.add(o)
					}
				}
				if (!hasMore) {
					Toast.makeText(activity, getString(R.string.no_more), Toast.LENGTH_SHORT).show()
				}
				mainView.isRefreshing = false
			})
		})
	}
	private fun loadArticles(page: Int, callback: (data: JsonArray) -> Boolean) {
		//调用API
		val req = Api.ApiRequest("article/list")
		when (type) {
			TYPE_ID -> {
				if (currentId == ALL_ID) {
					req.param.put("type", "all")
				} else {
					req.param.put("type", "id")
					req.param.put("val", currentId)
				}
			}
			TYPE_TAG -> {
				req.param.put("type", "tag")
				req.param.put("val", currentTag)
			}
		}
		req.param.put("page", page)
		Api.call(req, object: Api.Callback() {
			override fun onSuccess(data: JsonElement) {
				lastPage = data.asJsonObject.get("page").asNumber.toInt()
				callback(data.asJsonObject.get("list").asJsonArray)
			}
		})
	}
}